package com.ds.infrastructure.hyperspace.container.flow.handler.misc;

import com.ds.infrastructure.hyperspace.common.Container;
import com.ds.infrastructure.hyperspace.common.flow.FlowHandlerPipeline;
import com.ds.infrastructure.hyperspace.common.flow.handler.DuplexFlowHandler;
import com.ds.infrastructure.hyperspace.container.flow.context.HyperspaceDuplexFlowContext;
import groovy.lang.GroovyClassLoader;
import lombok.extern.slf4j.Slf4j;

/**
 * Use only when necessary
 * usage eg:
 *  -   handler: dynamicDuplexFlowHandler
 *      handlerParams: ['handler code block']
 *
 * @author  Weishaoying
 */
@Slf4j
public class DynamicDuplexFlowHandler implements DuplexFlowHandler<HyperspaceDuplexFlowContext> {

    private volatile DuplexFlowHandler<HyperspaceDuplexFlowContext> customDynamicDuplexFlowHandler;

    @Override
    public void handleInput(HyperspaceDuplexFlowContext duplexFlowContext, Object data) {
        if (customDynamicDuplexFlowHandler == null) {
            return;
        }
        customDynamicDuplexFlowHandler.handleInput(duplexFlowContext, data);
    }

    @Override
    public void handleOutput(HyperspaceDuplexFlowContext duplexFlowContext, Object data) {
        if (customDynamicDuplexFlowHandler == null) {
            return;
        }
        customDynamicDuplexFlowHandler.handleOutput(duplexFlowContext, data);
    }

    @Override
    public String handlerName() {
        return "dynamicDuplexFlowHandler";
    }

    @Override
    public void initHandlerParameters(Container container, FlowHandlerPipeline pipeline, String[] handlerParams) {
        try {
            Class dynamicDuplexFlowHandlerClass = new GroovyClassLoader().parseClass(handlerParams[0]);
            customDynamicDuplexFlowHandler = (DuplexFlowHandler<HyperspaceDuplexFlowContext>)
                    dynamicDuplexFlowHandlerClass.newInstance();
            customDynamicDuplexFlowHandler.initHandlerParameters(container, pipeline, handlerParams);
        } catch (Exception e) {
            log.error("Parse dynamicDuplexFlowHandlerClass failed!", e);
            customDynamicDuplexFlowHandler = null;
        }
    }
}
